package com.xing.web.controller;

import com.xing.domain.Account;
import com.xing.service.AccountService;
import com.xing.service.impl.AccountServiceImpl;
import com.xing.util.StringUtils;
import com.xing.util.TokenUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;

/*
 * 静，谦虚谨慎，心胸宽广容纳所有好的坏的、先苦后甜
 * day41_transaction
 * 2021/5/8 22:19
 */
@WebServlet(value = "/trans")
public class TransMoneyServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Account account = (Account) req.getSession().getAttribute("account");
        if(account==null){
            resp.sendRedirect(req.getContextPath()+"/login.jsp");
            return;
        }
        req.setCharacterEncoding("utf-8");
        String toCardNo = req.getParameter("toCardNo");
        String money = req.getParameter("money");
        String myTransToken = req.getParameter("myTransToken");
        if(StringUtils.isEmptry(toCardNo)){
            req.setAttribute("msg", "对方卡号不能为空");
            req.getRequestDispatcher("/message.jsp").forward(req, resp);
            return;
        }
        if(StringUtils.isEmptry(money)){
            req.setAttribute("msg", "转账金额不能为空");
            req.getRequestDispatcher("/message.jsp").forward(req, resp);
            return;
        }
        if(StringUtils.isEmptry(myTransToken)){
            req.setAttribute("msg", "令牌为空");
            req.getRequestDispatcher("/message.jsp").forward(req, resp);
            return;
        }
        //校验令牌
        String tranToken = (String) req.getSession().getAttribute("transToken");
        if(!myTransToken.equals(tranToken)){
            req.setAttribute("msg", "不要重复转账");
            req.getRequestDispatcher("/message.jsp").forward(req, resp);
            return;
        }

        try {
            AccountService accountService=new AccountServiceImpl();
            accountService.transMoney(account.getCardNo(),toCardNo,new BigDecimal(money));
            req.setAttribute("msg", "转账成功");
            //删除令牌
            TokenUtils.removeToken(req, "transToken");
            req.getRequestDispatcher("/message.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("msg", "转账失败"+e.getMessage());
            req.getRequestDispatcher("/message.jsp").forward(req, resp);
        }


    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
